' PicBasic Pro program to demonstrate the page-write
' capability of the 24LC256 serial memory.  This program
' will transfer 64 bytes of data to the memory before
' a pause is needed to complete the write.

' Set receive register to receiver enabled
DEFINE HSER_RCSTA       90h
' Set transmit register to transmitter enabled
DEFINE HSER_TXSTA       24h
' Set baud rate
DEFINE HSER_BAUD        9600



scl     VAR     PORTC.3                 ' Clock pin
sda     VAR     PORTC.4                 ' Data pin


addr    VAR     WORD                    ' Memory Address
data_array    VAR     BYTE[64]                ' Data array with location for checksum
i       VAR     BYTE                    ' Loop counter

        ADCON1 = 7                      ' Set PORTA and PORTE to digital
        
        
HSerout ["Programming", 10,13]

For i = 0 to 63							' Load the array with test data
	data_array[i] = i
Next i

 
'From the Microchip memory databook:  
'"Page write operations are limited to writing
'bytes within a single physical page,
'regardless of the number of bytes actually
'being written. Physical page boundaries
'start at addresses that are integer
'multiples of the page buffer size (or ‘page
'size’) and end at addresses that are
'integer multiples of [page size - 1]. If a
'Page Write command attempts to write
'across a physical page boundary, the
'result is that the data wraps around to the
'beginning of the current page (overwriting
'data previously stored there), instead of
'being written to the next page, as might be
'expected. It is, therefore, necessary for the
'application software to prevent page write
'operations that would attempt to cross a
'page boundary."

For addr = 0 To 32767 Step 64        ' Store $00 to all locations (for testing)

	I2CWrite sda,scl,$A0,addr,[STR data_array\64]  ' Send a 64-byte page
	HSerout ["."]				' Indicate progress           
	Pause 10						' Pause 10mS to let the write complete

Next addr


' Spot-check the data on the terminal screen
i = 0
Hserout [10,13, 10,13, "checking", 10,13]

For addr = 0 to 32767 Step 257		' read every 257th address
	i = i + 1

	I2CRead sda, scl, $A0, addr, [data_array[0]]		' Read a single byte from memory

	Hserout [HEX2 data_array[0], " "]		' To terminal with hex value 

	If (i & $0007) = 0 Then				' Break it into organized lines
		Hserout [10,13]					' 8 locations to a line
	Endif

Next addr				' Go get the next test

End




        
 
